package com.edu.scau.dao.implement;

import java.util.List;

import javax.annotation.Resource;

import com.edu.scau.dao.UserDao;
import com.edu.scau.dao.util.SessionFactoryUtil;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.edu.scau.entity.*;

@Component
@Transactional
public class UserDaoImpl implements UserDao {
	@Resource(name = "sessionFactory")
	private SessionFactory factory;

	public SessionFactory getFactory() {
		return factory;
	}

	public void setFactory(SessionFactory factory) {
		this.factory = factory;
	}

	public boolean save(User user) {
		try {
			Session session = factory.getCurrentSession();
			session.save(user);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public User get(int id) {
		Session session = factory.getCurrentSession();
		User user = session.get(User.class, id);
		return user;
	}

	public boolean update(User user) {
		try {
			// TODO Auto-generated method stub
			Session session = factory.getCurrentSession();
			session.update(user);
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;

	}

	public User getUserByPhone(String phone) {
		// TODO Auto-generated method stub
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(User.class);
		List<User> users = (List<User>) criteria.add(
				Restrictions.eq("phoneNumber", phone)).list();

		if (users.size() == 0) {
			return null;
		}

		return users.get(0);
	}

	public User getUserById(Integer id) {
		// TODO Auto-generated method stub
		Session session = factory.getCurrentSession();
		Criteria criteria = session.createCriteria(User.class);
		List<User> users = (List<User>) criteria.add(
				Restrictions.eq("id", id)).list();

		if (users.size() == 0) {
			return null;
		}

		return users.get(0);
	}

}
